package com.taotao.service.impl;

import com.taotao.common.ExceptionUtil;
import com.taotao.common.FtpUtil;
import com.taotao.common.IDUtils;
import com.taotao.service.PictureService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@PropertySource("classpath:/resources.properties")
public class PictureServiceImpl implements PictureService {

    @Value("${ftp.host}")
    private String ftpHost;
    @Value("${ftp.port}")
    private Integer ftpPort;
    @Value("${ftp.username}")
    private String ftpUserName;
    @Value("${ftp.password}")
    private String ftpPassword;
    @Value("${ftp.basePath}")
    private String ftpBasePath;
    @Value("${image.domain}")
    private String imageDomain;

    /**
     * 图片上传
     * @param picFile
     * @return
     */
    @Override
    public Map<String, Object> uploadPicture(MultipartFile picFile) {

        Map<String, Object> result = new HashMap<>();

        // 将图片上传到FTP服务器
        // 获取上传文件后缀名
        String suffixName = picFile.getOriginalFilename().substring(picFile.getOriginalFilename().lastIndexOf("."));

        // 生成文件名,带后缀
        String fileName = IDUtils.genImageNameByUUID() + suffixName;

        // 文件上传路径: 2019/07/28
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
        String filePath = simpleDateFormat.format(new Date());

        // 文件访问路径
        StringBuilder fileUrl = new StringBuilder();
        fileUrl.append(imageDomain);
        fileUrl.append("/");
        fileUrl.append(filePath);
        fileUrl.append("/");
        fileUrl.append(fileName);

        try {
            boolean flag = FtpUtil.uploadFile(ftpHost,ftpPort,ftpUserName,ftpPassword,ftpBasePath,filePath,fileName,picFile.getInputStream());
            if (!flag) {
                result.put("error",1);
                result.put("message","上传失败");
            }else {
                result.put("error",0);
                result.put("url",fileUrl.toString());
            }
        } catch (IOException e) {
            result.put("error",1);
            result.put("message","上传失败:" + ExceptionUtil.getStackTrace(e));
        }
        return result;
    }
}
